package com.hui.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.entity.bo.EshopUserBo;
import com.hui.entity.dao.ShopUser;
import com.hui.entity.dto.LocalUser;
import com.hui.entity.enums.AppFromEnum;
import com.hui.entity.enums.AppHttpCodeEnum;
import com.hui.entity.vo.EshopUserVo;
import com.hui.handler.exception.SystemException;
import com.hui.mapper.StoreOrderMapper;
import com.hui.mapper.UserBillMapper;
import com.hui.mapper.UserMapper;
import com.hui.model.auth.RegParam;
import com.hui.model.userlogin.LoginParam;
import com.hui.service.StoreOrderService;
import com.hui.service.UserService;
import com.hui.util.BeanCopyUtils;
import com.hui.util.IpUtil;
import com.hui.util.JwtUtil;
import com.hui.util.ResponseResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(EshopUser)表服务实现类
 *
 * @author hui
 * @since 2022-07-11 17:37:54
 */
@Service("eshopUserService")
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, ShopUser> implements UserService {

    private final StoreOrderMapper storeOrderMapper;
    private final UserBillMapper userBillMapper;
    private final UserMapper userMapper;
    @Autowired
    private StoreOrderService orderService;

    /**
     * 用户登录
     *
     * @param loginParam
     * @return
     */
    @Override
    public ResponseResult login(LoginParam loginParam) {
        /*查询用户是否存在*/
        LambdaQueryWrapper<ShopUser> lqw = new LambdaQueryWrapper();
        lqw.eq(StringUtils.hasText(loginParam.getUsername()), ShopUser::getUsername, loginParam.getUsername());
        lqw.eq(StringUtils.hasText(loginParam.getPassword()), ShopUser::getPassword, loginParam.getPassword());
        ShopUser user = getOne(lqw);
        /*查询用户是否存在end*/
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }
        LocalUser.setUser(user, user.getUid());
        /*返回带信息的token*/
        EshopUserBo eshopUserBo = BeanCopyUtils.copyBean(user, EshopUserBo.class); /*拷贝信息*/
        String jsonEshopUserBo = JSON.toJSONString(eshopUserBo);
        /*在创建jwt的同时，将用户信息保存到本地 LocalUser中*/
        String jwt = JwtUtil.createJWT(jsonEshopUserBo);/*封装用户信息到JWT*/
        String expiration = JwtUtil.getExpiration(jwt);//获取过期时间
//        EshopUserVo eshopUserVo = BeanCopyUtils.copyBean(user, EshopUserVo.class);/*拷贝用户信息*/
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("expires_time", expiration);
//        map.put("user", eshopUserVo);
        return ResponseResult.okResult(AppHttpCodeEnum.LOGIN_SUCCESS, map);
    }

    /**
     * 用户注册
     *
     * @param param
     * @return
     */
    @Override
    public ResponseResult register(RegParam param) {
        String ip = IpUtil.getLocalhostIp();
        ShopUser user = ShopUser.builder()
                .username(param.getAccount())
                .nickname(param.getNickname())
                .password(param.getPassword())
                .phone(param.getAccount())
                .addIp(ip)
                .lastIp(ip)
                .userType(AppFromEnum.H5.getValue())
                .build();
        boolean save = save(user);
        if (save) {
            return ResponseResult.okResult(AppHttpCodeEnum.REGISTER_SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.NO_REGISTER_SUCCESS);
    }

    /**
     * 用户支付订单有关
     *
     * @param uid
     * @param payPrice
     */
    @Override
    public void decPrice(Long uid, BigDecimal payPrice) {
        this.userMapper.decPrice(payPrice, uid);
    }

    /**
     * 用户支付订单有关
     *
     * @param uid
     */
    @Override
    public void incPayCount(Long uid) {
        this.userMapper.incPayCount(uid);
    }

    @Override
    public Double[] getUserMoney(Long uid) {
        //获取购买的商品 的消费总额
        double sumPrice = this.storeOrderMapper.sumPrice(uid);
        //从账单表获取累计充值金额
        double sumRechargePrice = this.userBillMapper.sumRechargePrice(uid);
        return new Double[]{sumPrice, sumRechargePrice};
    }

    @Override
    public EshopUserVo getNewYxUserById(ShopUser shopUser) {
        EshopUserVo userQueryVo = BeanCopyUtils.copyBean(shopUser, EshopUserVo.class);
        if (userQueryVo == null) {
            throw new SystemException(AppHttpCodeEnum.FAIL);
        } else {
            userQueryVo.setOrderStatusNum(this.orderService.orderData(shopUser.getUid()));//订单详情数据
            // userQueryVo.setCouponCount(this.storeCouponUserService.getUserValidCouponCount(shopUser.getUid())); // TODO 优惠券有关，暂时未实现
            //userQueryVo.setCheckStatus(this.systemStoreStaffService.checkStatus(shopUser.getUid(), (Integer) null)); // TODO 门店核销，暂时未实现
            //获取推广人数（可能）
            this.setUserSpreadCount(shopUser);
            return userQueryVo;
        }
    }

    private void setUserSpreadCount(ShopUser shopUser) {
        // TODO 作用不明，不知到为什么要更新用户信息
        int count = Math.toIntExact(this.baseMapper.selectCount(new LambdaQueryWrapper<ShopUser>().eq(ShopUser::getSpreadUid, shopUser.getUid())));
        shopUser.setSpreadCount(count);
        this.baseMapper.updateById(shopUser);
    }

}

